<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="javascript,对象," />





  <link rel="alternate" href="/atom.xml" title="前端-洋洋" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言因为超级营销无线装修用到了很多创建对象的方法，而不同的方法对于对象的设计，功能的实现会有很大的不同，所以最近在看代码的时候特意查了下创建对象的各种方法，在这里记录一下
-对象字面量-工厂模式-构造函数模式-原型模式-结合构造函数和原型模式-原型动态模式
1、对象字面量12345678var person = &amp;#123;    name : &amp;apos;Nicholas&amp;apos;;    a">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript中创建对象的模式汇总">
<meta property="og:url" content="http://html-js.site/2016/07/05/JavaScript中创建对象的模式汇总/index.html">
<meta property="og:site_name" content="前端-洋洋">
<meta property="og:description" content="前言因为超级营销无线装修用到了很多创建对象的方法，而不同的方法对于对象的设计，功能的实现会有很大的不同，所以最近在看代码的时候特意查了下创建对象的各种方法，在这里记录一下
-对象字面量-工厂模式-构造函数模式-原型模式-结合构造函数和原型模式-原型动态模式
1、对象字面量12345678var person = &amp;#123;    name : &amp;apos;Nicholas&amp;apos;;    a">
<meta property="og:image" content="http://html-js.site/images/page/createObject/1.png">
<meta property="og:image" content="http://html-js.site/images/page/createObject/2.png">
<meta property="og:image" content="http://html-js.site/images/page/createObject/3.png">
<meta property="og:updated_time" content="2016-07-05T10:06:46.493Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaScript中创建对象的模式汇总">
<meta name="twitter:description" content="前言因为超级营销无线装修用到了很多创建对象的方法，而不同的方法对于对象的设计，功能的实现会有很大的不同，所以最近在看代码的时候特意查了下创建对象的各种方法，在这里记录一下
-对象字面量-工厂模式-构造函数模式-原型模式-结合构造函数和原型模式-原型动态模式
1、对象字面量12345678var person = &amp;#123;    name : &amp;apos;Nicholas&amp;apos;;    a">
<meta name="twitter:image" content="http://html-js.site/images/page/createObject/1.png">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://html-js.site/2016/07/05/JavaScript中创建对象的模式汇总/"/>

  <title> JavaScript中创建对象的模式汇总 | 前端-洋洋 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?ca98d1db5559cb59848d14443c7fa5dd";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">前端-洋洋</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">专注于前端</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                JavaScript中创建对象的模式汇总
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-07-05T14:19:25+08:00" content="2016-07-05">
              2016-07-05
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/07/05/JavaScript中创建对象的模式汇总/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/07/05/JavaScript中创建对象的模式汇总/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>因为超级营销无线装修用到了很多创建对象的方法，而不同的方法对于对象的设计，功能的实现会有很大的不同，所以最近在看代码的时候特意查了下<b>创建对象</b>的各种方法，在这里记录一下</p>
<p>-对象字面量<br>-工厂模式<br>-构造函数模式<br>-原型模式<br>-结合构造函数和原型模式<br>-原型动态模式</p>
<h3 id="1、对象字面量"><a href="#1、对象字面量" class="headerlink" title="1、对象字面量"></a>1、对象字面量</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var person = &#123;</span><br><span class="line">    name : &apos;Nicholas&apos;;</span><br><span class="line">    age : &apos;22&apos;;</span><br><span class="line">    job :&quot;software Engineer&quot;</span><br><span class="line">    sayName: function() &#123;</span><br><span class="line">      alter(this.name);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>例子中创建一个名为person的对象，并为它添加了三个属性（name,age,job）和一个方法（sayName()），其中，sayName()方法用于显示this.name(被解析为person.name)的值。</p>
<p><b>对象字面量可以用来创建单个对象，但这个方法有个明显的缺点：使用同一个接口创建很多对象，会产生大量重复的代码。</b></p>
<h3 id="2、工厂模式"><a href="#2、工厂模式" class="headerlink" title="2、工厂模式"></a>2、工厂模式</h3><p>工厂模式是软件工程领域中一种广为人知的设计模式，工厂模式抽象了创建具体对象的过程，用函数来封装以特定的接口创建对象的细节。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">function createPerson(name,age,job)&#123;</span><br><span class="line">  var o = new object&#123;&#125;;</span><br><span class="line">  o.name=name;</span><br><span class="line">  o.age=age;</span><br><span class="line">  o.job=job;</span><br><span class="line">  o.sayName=function()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">  &#125;;</span><br><span class="line">  return o;</span><br><span class="line">&#125;</span><br><span class="line">var person1=creatPerson(&quot;Nicholas&quot;,22,&quot;software Engineer&quot;);</span><br><span class="line">var person2=creatPerson(&quot;Greg&quot;,24,&quot;student&quot;);</span><br></pre></td></tr></table></figure>
<p>函数creatPerson{}能够根据接受的参数构建一个包含所有必要信息的Person对象。可以无数次的调用这个函数，每次都会返回一个包含三个属性一个方法的对象。</p>
<p><b>工厂模型虽然解决了创建多个相似对象的问题，却没有解决对象识别的问题（即怎么知道一个对象的类型）。 </b></p>
<h3 id="3、构造函数模式"><a href="#3、构造函数模式" class="headerlink" title="3、构造函数模式"></a>3、构造函数模式</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">function Person(name,age,job) &#123;</span><br><span class="line">  this.name = name;</span><br><span class="line">  this.age = age;</span><br><span class="line">  this.job = job;</span><br><span class="line">  this.sayName = function() &#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">//通过new操作符创建Person的实例</span><br><span class="line">var person1 = new Person(&quot;Nicholas&quot;,22,&quot;software Engineer&quot;);</span><br><span class="line">var person2 = new Person(&quot;Greg&quot;,24,&quot;student&quot;);</span><br><span class="line">person1.sayName(); //Nicholas</span><br><span class="line">person2.sayName(); //Greg</span><br></pre></td></tr></table></figure>
<p><b>与工厂模式不同的是</b><br>没有显示的创建对象</p>
<p>直接将属性和方法赋给了this对象</p>
<p>没有return语句</p>
<p>创建Person的新实例，必须使用new操作符。调用构造函数的4个步骤：</p>
<p>创建一个新对象</p>
<p>将构造函数的作用域赋给新对象（this指向了这个新对象）</p>
<p>执行构造函数中的代码</p>
<p>返回新对象</p>
<p>这个例子中创建的所有对象既是Object的实例，也是Person实例。可以通过instanceof操作符验证。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(person1 instanceof Object);//true</span><br></pre></td></tr></table></figure>
<p>构造函数模式也有自己的问题，实际上，sayName方法在每个实例上都会被重新创建一次，需要注意的是，通过实例化创建的方法并不相等，以下代码可以证明<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(person1.sayName == person2.sayName);//false</span><br></pre></td></tr></table></figure></p>
<p>可以将方法移到构造器的外部作为全局函数来解决这个问题。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function Person(name,age,job) &#123;</span><br><span class="line">  this.name = name;</span><br><span class="line">  this.age = age;</span><br><span class="line">  this.job = job;  </span><br><span class="line">&#125;</span><br><span class="line">function sayName() &#123;</span><br><span class="line">  alert(this.name);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在全局下创建的全局函数实际上只能被经由Person创建的实例调用，这就有点名不副实了；如果对象需要定义很对方法，那么就要定义很多个全局函数，缺少封装性。</p>
<h3 id="4、原型模式"><a href="#4、原型模式" class="headerlink" title="4、原型模式"></a>4、原型模式</h3><p>JavaScript中创建的每个函数都有一个prototype（原型）属性，它是一个指针，指向一个对象，包含了可以由特定类型的所有实例共享的属性和方法（让所有的对象实例共享它的属性和方法）<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function Person() &#123;&#125;</span><br><span class="line">  Person.prototype.name =&quot;Nicholas&quot;;</span><br><span class="line">  Person.prototype.age = 22;</span><br><span class="line">  Person.prototype.job = &quot;software Engineer&quot;;  </span><br><span class="line">  Person.prototype.sayName()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">  &#125;;</span><br><span class="line"> var person1 = new Person();</span><br><span class="line"> person1.sayName(); //Nicholas</span><br><span class="line">alert(person1.sayName == person2.sayName);//true</span><br></pre></td></tr></table></figure></p>
<p>以上代码做了这几件事情：</p>
<p>定义了一个构造函数Person，Person函数自动获得一个prototype属性，该属性默认只包含一个指向Person的constructor属性</p>
<p>通过Person.prototype添加三个属性，和一个方法</p>
<p>创建一个Person的实例，随后在实例上调用了sayName()方法 </p>
<p>使用Person构造函数和Person.prototype创建实例的代码为例，展示个对象之间的关系 </p>
<p><img src="/images/page/createObject/1.png"></p>
<p>图中展示了Person构造函数、Person的原型属性以及Person的两个实例，之间的关系。Person.prototype指向了原型对象，Person.prototype.constructor有指回了Person。原型对象中除了包含constructor属性，还包含后来添加的其他属性和方法，Person的两个实例person1和person2都包含一个内部属性，该属性仅指向Person.prototype。 </p>
<p><b>sayName()方法的调用过程：</b></p>
<p>在person1实例上查找sayame()方法，发现没有这个方法，于是追溯到person1的原型</p>
<p>在person1的原型上查找sayame()方法，有这个方法，于是调用该方法</p>
<p>基于这样一个查找过程，我们可以通过在实例上定义原型中的同名属性，来阻止该实例访问原型上的同名属性，需要注意的是，这样做并不会删除原型上的同名属性，仅仅是阻止实例访问。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">function Person() &#123;&#125;</span><br><span class="line">  Person.prototype.name =&quot;Nicholas&quot;;</span><br><span class="line">  Person.prototype.age = 22;</span><br><span class="line">  Person.prototype.job = &quot;software Engineer&quot;;  </span><br><span class="line">  Person.prototype.sayName()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">  &#125;;</span><br><span class="line"> var person1 = new Person();</span><br><span class="line"> var person2 = new Person();</span><br><span class="line"> person1.name=&quot;Greg&quot;</span><br><span class="line">alert(person1.name) //Greg 来自实例</span><br><span class="line">alert(person2.name) //Nicholas 来自原型</span><br></pre></td></tr></table></figure>
<p>使用delete操作符可以完全删除实例属性<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">delete person1.name;</span><br><span class="line">alert(person1.name) //Nicholas 来自原型</span><br></pre></td></tr></table></figure></p>
<p>使用hasOwnProperty()方法可以检测一个属性是存在于实例还是原型中<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">function Person() &#123;&#125;</span><br><span class="line">  Person.prototype.name =&quot;Nicholas&quot;;</span><br><span class="line">  Person.prototype.age = 22;</span><br><span class="line">  Person.prototype.job = &quot;software Engineer&quot;;  </span><br><span class="line">  Person.prototype.sayName()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">  &#125;;</span><br><span class="line"> var person1 = new Person();</span><br><span class="line"> var person2 = new Person();</span><br><span class="line"> alert(person1,hasOwnProperty(&quot;name&quot;));//false</span><br><span class="line"> person1.name=&quot;Greg&quot;</span><br><span class="line">alert(person1.name) //Greg 来自实例</span><br><span class="line"> alert(person1,hasOwnProperty(&quot;name&quot;));//true</span><br><span class="line">alert(person2.name) //Nicholas 来自原型</span><br><span class="line"> alert(person2,hasOwnProperty(&quot;name&quot;));//false</span><br><span class="line"> delete person1.name;</span><br><span class="line">alert(person1.name) //Nicholas 来自原型</span><br><span class="line"> alert(person1,hasOwnProperty(&quot;name&quot;));//false</span><br></pre></td></tr></table></figure></p>
<p>下图展示了在不同情况下实例与原型之间的关系<br><img src="/images/page/createObject/2.png"></p>
<h3 id="5、简单的原型语法"><a href="#5、简单的原型语法" class="headerlink" title="5、简单的原型语法"></a>5、简单的原型语法</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function Person() &#123;&#125;</span><br><span class="line"> Person.prototype=&#123;</span><br><span class="line"> name ：&quot;Nicholas&quot;,</span><br><span class="line"> age ： 22,</span><br><span class="line"> job ： &quot;software Engineer&quot;, </span><br><span class="line"> sayName：function()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br></pre></td></tr></table></figure>
<p>在上面的代码中constructor属性不再指向Person了，通过constructor无法确定对象的类型了。可以像下面这样特意将他设置回适当的值<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function Person() &#123;&#125;</span><br><span class="line"> Person.prototype=&#123;</span><br><span class="line"> constructor:Person,</span><br><span class="line"> name ：&quot;Nicholas&quot;,</span><br><span class="line"> age ： 22,</span><br><span class="line"> job ： &quot;software Engineer&quot;,  </span><br><span class="line"> sayName：function()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br></pre></td></tr></table></figure></p>
<p>重设constructor属性会导致它的[[Enumerable]]特性被设置为true，默认情况，原生的constructor属性是不可枚举的，可以使用Object.defineProperty()方法来改变<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Object.defineProperty(Person.prototype,&quot;constructor&quot;,&#123;</span><br><span class="line">  enumerable:false,</span><br><span class="line">  value:Person</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<p>原型中查找值的过程是一次搜索，原型对象所做的任何修改都能从实例上立即反应出来<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var friend=new Person();</span><br><span class="line">Person.prototype.sayHi=function()&#123;</span><br><span class="line">  alert(&quot;hi);</span><br><span class="line">&#125;</span><br><span class="line">friend,sayHi();//&quot;hi&quot;(没有问题)</span><br></pre></td></tr></table></figure></p>
<p>person实例是在添加新方法之前创建的，但仍可以访问新添加的方法，原因是实例与原型之间的松散连接关系 </p>
<p>重写原型对象后的情况<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">function Person() &#123;&#125;</span><br><span class="line">var friend=new Person();</span><br><span class="line"> Person.prototype=&#123;</span><br><span class="line"> name ：&quot;Nicholas&quot;,</span><br><span class="line"> age ： 22,</span><br><span class="line"> job ： &quot;software Engineer&quot;, </span><br><span class="line"> sayName：function()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">  friend.sayName();//error</span><br></pre></td></tr></table></figure></p>
<p>调用friend.sayName()时发生错误的原因是，friend指向的原型中不包含以该字段命名的属性，如下图。<br><img src="/images/page/createObject/3.png"></p>
<p><b>原型对象的问题</b><br>原型对象省略了为构造函数传递初始化参数这一环节，所有势力在默认情况下都取得相同的属性值。原型模型最大的问题是有其共享本性所导致的。当原型模型包含引用类型的属性来说，问题就比较严重了。来看下面的例子。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">function Person() &#123;&#125;</span><br><span class="line"> Person.prototype=&#123;</span><br><span class="line"> constructor:Person,</span><br><span class="line"> name ：&quot;Nicholas&quot;,</span><br><span class="line"> age ： 22,</span><br><span class="line"> job ： &quot;software Engineer&quot;,  </span><br><span class="line"> friends:[&quot;Shelby&quot;,&quot;Court&quot;],</span><br><span class="line"> sayName：function()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">  var person1=new Person();</span><br><span class="line">  var person2=new Person();</span><br><span class="line">  person1.friend.push(&quot;Van&quot;);</span><br><span class="line">  alert(person1.friends);//&quot;Shelby,Court,Van&quot;</span><br><span class="line">  alert(person2.friends);//&quot;Shelby,Court,Van&quot;</span><br><span class="line"> alert(person1.friends==person2.friends);//true</span><br></pre></td></tr></table></figure></p>
<h3 id="5、组合使用构造函数模式和原型模式"><a href="#5、组合使用构造函数模式和原型模式" class="headerlink" title="5、组合使用构造函数模式和原型模式"></a>5、组合使用构造函数模式和原型模式</h3><p>组合使用构造函数模式和原型模式中，构造函数用于定义实例属性，原型模型用于定义方法和共享的属性。这样每个实例都会有自己的一份实例属性的副本，同时也可以共享对方法的引用，最大限度的节省了内存。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">function Person(name,age,job) &#123;</span><br><span class="line">  this.name = name;</span><br><span class="line">  this.age = age;</span><br><span class="line">  this.job = job;  </span><br><span class="line">  this.friends=[&quot;Shelby&quot;,&quot;Court&quot;];</span><br><span class="line">&#125;</span><br><span class="line">Person.prototype=&#123;</span><br><span class="line"> constructor：Person，</span><br><span class="line"> sayName：function()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">var person1=new Person(&quot;Nicholas&quot;,22,&quot;software Engineer&quot;);</span><br><span class="line">var person2 = new Person(&quot;Greg&quot;,24,&quot;student&quot;);</span><br><span class="line">person1.friend.push(&quot;Van&quot;);</span><br><span class="line">  alert(person1.friends);//&quot;Shelby,Court,Van&quot;</span><br><span class="line">  alert(person2.friends);//&quot;Shelby,Court&quot;</span><br><span class="line"> alert(person1.friends==person2.friends);//false</span><br><span class="line"> alert(person1.sayName==person2.sayName);//true</span><br></pre></td></tr></table></figure>
<h3 id="6、动态原型模式"><a href="#6、动态原型模式" class="headerlink" title="6、动态原型模式"></a>6、动态原型模式</h3><p>原型动态模式将需要的所有信息都封装到构造函数中，通过if语句判断原型中的某个属性是否存在，若不存在（在第一次调用这个构造函数的时候），执行if语句内部的原型初始化代码。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">function Person(name,age) &#123;</span><br><span class="line">  this.name = name;</span><br><span class="line">  this.age = age;</span><br><span class="line">  this.job =job;</span><br><span class="line">//方法</span><br><span class="line">  if(typeof this.sayName != &apos;function&apos;) &#123;</span><br><span class="line">  Person.prototype.sayName = function() &#123;</span><br><span class="line">      alert(this.name);</span><br><span class="line">    &#125;;   </span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">var friend = new Person(&apos;Nicholas&apos;,&apos;22&apos;,&apos;Software Engineer&apos;);//初次调用构造函数，此时修改了原型</span><br><span class="line">var person2 = new Person(&apos;amy&apos;,&apos;21&apos;);//此时sayName()方法已经存在，不会再修改原型</span><br></pre></td></tr></table></figure>
      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/wechat.jpg" alt="wangyang WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay.jpg" alt="wangyang Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/javascript/" rel="tag">#javascript</a>
          
            <a href="/tags/对象/" rel="tag">#对象</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/06/28/自己实现lazyload/" rel="next" title="自己实现lazyload">
                <i class="fa fa-chevron-left"></i> 自己实现lazyload
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/07/14/一些jquery小技巧/" rel="prev" title="一些jquery小技巧">
                一些jquery小技巧 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/07/05/JavaScript中创建对象的模式汇总/"
           data-title="JavaScript中创建对象的模式汇总" data-url="http://html-js.site/2016/07/05/JavaScript中创建对象的模式汇总/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/default_avatar.jpg"
               alt="wangyang" />
          <p class="site-author-name" itemprop="name">wangyang</p>
          <p class="site-description motion-element" itemprop="description">专注于前端</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">15</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/WangYang-Rex" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/2690568063/" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="617418875" target="_blank" title="QQ">
                  
                    <i class="fa fa-fw fa-qq"></i>
                  
                  QQ
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:617418875@qq.com" target="_blank" title="Mail">
                  
                    <i class="fa fa-fw fa-envelope-o"></i>
                  
                  Mail
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友链
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://http://moshui.site/" title="moxhuis" target="_blank">moxhuis</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://indexof.site/" title="indexof" target="_blank">indexof</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://xiaoqiang730730.github.io/" title="xiaoqiang" target="_blank">xiaoqiang</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1、对象字面量"><span class="nav-number">2.</span> <span class="nav-text">1、对象字面量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2、工厂模式"><span class="nav-number">3.</span> <span class="nav-text">2、工厂模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3、构造函数模式"><span class="nav-number">4.</span> <span class="nav-text">3、构造函数模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4、原型模式"><span class="nav-number">5.</span> <span class="nav-text">4、原型模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5、简单的原型语法"><span class="nav-number">6.</span> <span class="nav-text">5、简单的原型语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5、组合使用构造函数模式和原型模式"><span class="nav-number">7.</span> <span class="nav-text">5、组合使用构造函数模式和原型模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6、动态原型模式"><span class="nav-number">8.</span> <span class="nav-text">6、动态原型模式</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wangyang</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"html-js"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  

  

  

  

</body>
</html>
